/**
 * Created by Will Bean on 2016/8/21.
 */
import React, {PropTypes, Component} from 'react'
import fetch from 'isomorphic-fetch'
import {Link} from 'react-router'

import Table from './Table'
import SelectInput from './SelectInput'
import NavLink from './NavLink'
import style from './addStore.css'
import CheckboxInput from './CheckboxInput'

import {myAjax, ROOTURL, getAuthShop} from '../publicAPI/publicAPI'

var servantServiceList = [];
var servantToService = {};//每个理发师对应的服务类型

class BarberServiceM extends Component {

    constructor(props, context) {
        super(props, context);
        console.log("初始化");

        this.state = {
            delete: false,
            deleteId: -1,
            serviceList: [],
            currentShopId: 1,
            storeList: [],
            ddServiceList: [],
            servantList: [],
            hasBeenMounted: false,
            buttonMsg: "保存"
        };// 初始化状态

        this.clickingSaveButton =  false;
    }

    getStoreNameList() {
        var arr = [];
        this.state.storeList.map((store, index)=> {
            arr.push((<option key={index} value={store.id}>{store.dname}</option>))
        });
        return arr;
    }

    handleSelectChange(val) {
        this.deletServiceAttr();
        servantServiceList = [];

        // servantToService = {};
        var _this = this;
        fetch(ROOTURL + 'serv/shop/aggregated/search.api', {
            method: 'POST',
            body: JSON.stringify({
                "where": {"shopId": [["eq", val]], "dd": [["eq", false]]},
                "order": [["id", "asc"]]
            })
        }).then(res=> {
            if (res.ok) {
                res.json().then(data=> {console.log(data)
                    _this.setState({
                        serviceList: data
                    })
                })
            }
        });
        fetch(ROOTURL + 'serv/shop/search.api', {
            method: 'POST',
            body: JSON.stringify({
                "where": {"shopId": [["eq", val]], "dd": [["eq", true]]},
                "order": [["id", "asc"]]
            })
        }).then(res=> {
            if (res.ok) {
                res.json().then(data=> {
                    _this.setState({
                        ddServiceList: data
                    })
                })
            }
        });
        fetch(ROOTURL + 'servant/profile/search.api ', {
            method: 'POST',
            body: JSON.stringify({
                "where": {"shopId": [["eq", val]], "dd": [["eq", false]]},
                "order": [["id", "asc"]]
            })
        }).then(res=> {
            if (res.ok) {
                res.json().then(data=> {
                    var d = {};
                    var i = 0;
                    if(data.length){
                        data.map(servant=> {
                            fetch(ROOTURL + 'serv/concrete/aggregated/search.api', {
                                method: "POST",
                                body: JSON.stringify({
                                    "where": {"servantId": [["eq", servant.id]]},
                                    "order": [["id", "asc"]]
                                })
                            }).then(res=> {
                                i++;
                                if (res.ok) {
                                    return res.json()
                                }
                            }).then(data2=> {
                                servantToService[servant.id] = data2;
                                data2 ? data2.map(service=> {
                                    d['serviceServant' + servant.id + '_' + service.shopServiceId + '_' + service.id] = !service.dd;
                                    servantServiceList.push('serviceServant' + servant.id + '_' + service.shopServiceId + '_' + service.id);
                                }) : null;
                                if (i == data.length) {
                                    d['servantList'] = data;
                                    _this.setState(d)
                                }
                            });
                        });
                    }else {
                        _this.setState({
                            servantList : data
                        })
                    }

                })
            }
        });
    }

    componentWillMount() {
        console.log("将安装");
        if (!this.state.hasBeenMounted) {
            servantServiceList = [];
            servantToService = {};
            this.setState({hasBeenMounted: true});
            var url = ROOTURL + 'shop/search.api';//获取门店列表，用以门店选择器
            var _this = this;
            getAuthShop({
                "where": {"dd": [["eq", false]]},
                "order": [["id", "asc"]]
            },function (data) {
                var shopId = _this.props.params.id ? _this.props.params.id : data[0].id;
                fetch(ROOTURL + 'serv/shop/aggregated/search.api', {
                    method: 'POST',
                    body: JSON.stringify({
                        "where": {"shopId": [["eq", shopId]], "dd": [["eq", false]]},
                        "order": [["id", "asc"]]
                    })
                }).then(res=> {
                    if (res.ok) {
                        res.json().then(data=> {
                            _this.setState({
                                serviceList: data
                            })
                        })
                    }
                });
                fetch(ROOTURL + 'serv/shop/search.api', {
                    method: 'POST',
                    body: JSON.stringify({
                        "where": {"shopId": [["eq", shopId]], "dd": [["eq", true]]},
                        "order": [["id", "asc"]]
                    })
                }).then(res=> {
                    if (res.ok) {
                        res.json().then(data=> {
                            _this.setState({
                                ddServiceList: data
                            })
                        })
                    }
                });
                fetch(ROOTURL + 'servant/profile/search.api ', {
                    method: 'POST',
                    body: JSON.stringify({
                        "where": {"shopId": [["eq", shopId]], "dd": [["eq", false]]},
                        "order": [["id", "asc"]]
                    })
                }).then(res=> {
                    if (res.ok) {
                        res.json().then(data=> {
                            var d = {};
                            var i = 0;
                            data.map(servant=> {
                                fetch(ROOTURL + 'serv/concrete/aggregated/search.api', {
                                    method: "POST",
                                    body: JSON.stringify({
                                        "where": {"servantId": [["eq", servant.id]],"dd":[["eq",false]]},
                                        "order": [["id", "asc"]]
                                    })
                                }).then(res=> {
                                    i++;
                                    if (res.ok) {
                                        return res.json()
                                    }
                                }).then(data2=> {
                                    servantToService[servant.id] = data2;
                                    data2 ? data2.map(service=> {
                                        d['serviceServant' + servant.id + '_' + service.shopServiceId + '_' + service.id] = !service.dd;
                                        servantServiceList.push('serviceServant' + servant.id + '_' + service.shopServiceId + '_' + service.id);
                                    }) : null;
                                    if (i == data.length) {
                                        d['servantList'] = data;
                                        _this.setState(d)
                                    }
                                });
                            });
                        })
                    }
                });
                _this.setState({
                    storeList: data,
                    currentShopId: shopId
                })
            })
        }

    }

    componentDidMount() {
        console.log("安装成功")
    }

    handleDelete(id) {
        this.setState({
            delete: !this.state.delete,
            deleteId: id
        })
    }

    isInServiceList(s) {
        servantServiceList.map(ser=> {
            if (s == ser) {
                return true
            }
        });
        return false
    }

    getObjLength(obj){
        var count = 0;
        for(var o in obj){
            count++;
        }
        return count;
    }

    deletServiceAttr(){
        var state = this.state;
        for (var s in state) {
            if (s.indexOf('serviceServant') >= 0) {
                delete this.state[s];
            }
        }
    }

    handlesave() {
        if (this.clickingSaveButton) {
            return;
        } else {
            this.clickingSaveButton = true;
            this.setState({
                buttonMsg: '保存中...'
            })
            setTimeout(() => {
                this.clickingSaveButton = false;
                this.setState({
                    buttonMsg: "保存"
                })
            }, 2500)
        }
        var serList = [];
        var serState = this.findServantState();
        var length = this.getObjLength(serState);
        var count = 0;
        for (var s in serState) {
            var arr = s.match(/serviceServant([\d]+)_([\d]+)_([\d]+)/);
            if (arr[3] != '0') {//原有数据   无需新建  -------理论上不会进入这段代码中
                if (serState[s]) {//update
                            fetch(ROOTURL+'serv/concrete/instance.api?singleton=true&id='+arr[3],{
                                method : "POST",
                                body: JSON.stringify({
                                    servant : arr[1],
                                    shopService : arr[2],
                                    dd: false
                                })
                            }).then(res=>{
                                if(res.ok && ++count == length){
                                    // alert('保存成功')
                                }
                            })
                } else {//delete
                    fetch(ROOTURL+'serv/concrete/instance.api?id='+arr[3],{
                        method: 'delete',
                        body : JSON.stringify({})
                    }).then(res=>{
                        if(res.ok && ++count == length){
                            // alert('保存成功')
                        }
                    })
                }
            } else if (serState[s] && arr[3] == '0') {//新建
                        fetch(ROOTURL+'serv/concrete/instance.api?singleton=true',{
                            method: 'post',
                            body: JSON.stringify({
                                servant : arr[1],
                                shopService : arr[2]
                            })
                        }).then(res=>{
                            if(res.ok && ++count == length){
                            }
                        })
            }
        }

    }

    findServantState() {
        var d = {};
        var state = this.state;
        for (var s in state) {
            if (s.indexOf('serviceServant') >= 0) {
                d[s] = state[s];
            }
        }
        return d;
    }

    handleStoreDelete() {
        var url = ROOTURL + 'serv/shop/instance.api?id=' + this.state.deleteId;
        this.setState({
            delete: !this.state.delete
        });
        fetch(url, {
            method: 'delete',
            // mode : 'no-cors',
            body: JSON.stringify({})
        }).then(res=> {
            if (res.ok) {
                res.json().then(data=> {
                    location.href = '/ShopServiceM' + this.state.currentShopId
                })
            }
        });
    }

    getServantServiceId(str){
        var ss ;
        servantServiceList.map(s=>{
            if( s.indexOf(str) >=0){
                ss = s;
            }
        });
        return ss;
    }

    tHeadServant(list) {
        var data = [
            {name: "标识"}
        ];
        list.map(servant=> {
            data.push({name: servant.meta.name})
        });
        const _headArr = [];
        _headArr.push(data.map((item, index) => <th role="1" key={index}>{item.name}</th>));
        return _headArr;
    }

    tBodyServant(dataList, deleteBtn) {
        return dataList.map(item => <tr key={item.id}>
            <td>{item.meta && item.meta.icon ? <img style={{maxWidth: '50px',maxHeight:'50px',verticalAlign:'middle'}}
                                                    src={ROOTURL + 'asset/images/get.api?hashed=' + item.meta.icon}/> : null}{item.name}/{item.dname}</td>
            {this.state.servantList.map((servant, index)=>{
                var ss = this.getServantServiceId.bind(this)('serviceServant'+servant.id + '_'+ item.id);console.log(ss)
                var state = ss ? this.state[ss] : this.state['serviceServant'+servant.id + '_'+ item.id + '_0'];
                return (
                        <td key={index}><CheckboxInput isCheck={state?true:false}
                                                       onChange={val=>{
                    var d = {};d[ss ? ss : 'serviceServant'+servant.id + '_'+ item.id+'_0'] = val;this.setState(d);
                }}/></td>
                    )
                }
            )}
        </tr>)
    }

    //render thead
    tHead() {
        var data = [
            {name: "id"},
            {name: "图标"},
            {name: "标识"},
            {name: "显示名"},
            {name: "基础价格"},
            {name: "服务时长"},
            {name: "并行工作荷载"},
            {name: "扩展于"},
            {name: "操作"}
        ];
        const _headArr = [];
        const _width = {
            "0": "5%",
            "1": "5%",
            "2": "10%",
            "3": "10%",
            "4": "10%",
            "5": "10%",
            "6": "10%",
            "7": "20%",
            "8": "20%"
        };
        _headArr.push(data.map((item, index) => <th style={{width: _width[index]}} role="1"
                                                    key={index}>{item.name}</th>))
        return _headArr;
    }

    tBody(dataList, deleteBtn) {

        return dataList.map(item => <tr key={item.id}>
            <td>{item.id}</td>
            <td>{item.meta && item.meta.icon ? <img style={{maxWidth: '50px',maxHeight:'50px',verticalAlign:'middle'}}
                                                    src={ROOTURL + 'asset/images/get.api?hashed=' + item.meta.icon}/> : null}</td>
            <td>{item.name}</td>
            <td>{item.dname}</td>
            <td>{item.cost0}</td>
            <td>{item.duration}</td>
            <td>{item.workload}</td>
            <td>{item.workload}</td>
            <td>
                <span><NavLink to={`/ShopServiceM/ShopServiceEditor/${item.id}`}
                               className="rbtn green">编辑</NavLink></span>
                {deleteBtn ?
                    <span style={{marginLeft: "15px"}}><a className="rbtn red" onClick={()=>this.handleDelete(item.id)}>删除</a></span> : null }
                <span style={{marginLeft: "15px"}}><NavLink
                    to={`/ShopServiceM/ShopServiceEditor${'Preview'}/${item.id}`}
                    className="rbtn green">预览</NavLink></span>
            </td>
        </tr>)
    }

    render() {
        console.log(this.state)
        return (
            <div className="right-wapper " style={{height:'auto'}}>
                <div className="rt-wrap">
                    <h2 className="catagory">
                        <Link to={`/PrototypeServiceM`}><span className={style['cata-title']}>服务原型</span></Link>
                        <Link to={`/ShopServiceM`}><span className={style['cata-title']}>门店服务类型</span></Link>
                        <Link to={`/BarberServiceM`}><span className={style['cata-title-current']}>理发师服务类型</span></Link>
                    </h2>
                    <div style={{margin:'10px 0'}}>
                        <label style={{paddingRight:'10px'}}>门店选择器</label>
                        <SelectInput optionsData={this.getStoreNameList()}
                                     val={this.state.currentShopId}
                                     onChange={val=>{this.setState({currentShopId:val});
                                     this.handleSelectChange.bind(this)(val)
                                     }}/>
                    </div>
                    <div style={{margin:'20px 0 10px'}}>
                        <label>当前提供的服务项目</label>
                    </div>
                    <Table tHead={this.tHeadServant.bind(this)(this.state.servantList)}
                           tBody={this.tBodyServant.bind(this)(this.state.serviceList,true)}/>
                    <button id="submit" className={style['main_btn']}
                            style={{backgroundColor: '#2285c7',border: '1px solid #1e77b3',margin:'20px 0 0'} }
                            onClick={this.handlesave.bind(this)}>{this.state.buttonMsg}
                    </button>
                    {this.state.ddServiceList.length ? (<div>
                        <div style={{margin:'30px 0 10px'}}>
                            <label>停止运营的服务项目</label>
                        </div>
                        <Table tHead={this.tHead.bind(this)()}
                               tBody={this.tBody.bind(this)(this.state.ddServiceList,false)}/></div> ) : null}
                </div>
                { this.state.delete ?
                    <div id={style.msgDialog}>
                        <div className={style['msgDialog_div']}><h3 id={style['msgDialog_title']}>删除提示？</h3><p
                            id={style['msgDialog_content']}>确认删除？</p>
                            <div className={style['msgDialog_button']}>
                                <button id={style['msgDialog_yes']} onClick={this.handleStoreDelete.bind(this)}>确定
                                </button>
                                <button id={style['msgDialog_no']}
                                        onClick={()=>this.setState({delete: !this.state.delete})}>取消
                                </button>
                            </div>
                        </div>
                    </div> : null}
            </div>
        )
    }
}

export default BarberServiceM
